package com.jiesen.base.modules.login.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.jiesen.base.baseDao.RedisServiceImpl;
import com.jiesen.base.modules.login.jsLoginUser.model.JsLoginUser;
import com.jiesen.base.modules.login.jsLoginUser.model.UserLogin;
import com.jiesen.base.modules.login.jsLoginUser.service.JsLoginUserService;
import com.jiesen.base.modules.login.jsLoginUser.utils.JsLoginUserUtil;
import com.jiesen.base.modules.login.jsPermission.model.Permission;
import com.jiesen.base.modules.login.jsRole.model.JsRole;
import com.jiesen.base.utils.JWTUtil;
import com.jiesen.base.utils.PasswordUtils;
import com.jiesen.base.utils.R;
import com.jiesen.base.utils.TreeUtil;

/**
 * 用户登录接口
 */
@RestController
@CrossOrigin
public class LoginController {

    @Autowired
    private JsLoginUserService jsLoginUserService;

    @Autowired
    private RedisServiceImpl redisService;

    //登录获取token
    @PostMapping("/login")
    public R loginx(@RequestBody UserLogin userLogin,HttpServletRequest request) {
        String username = userLogin.getUsername();
        String password = userLogin.getPassword();
        if (username == null || password == null) {
            return R.error("没有输入用户名或密码");
        }
        String token1 = request.getHeader("token");
        if(token1!=null){
            try {
                redisService.remove(token1);
            } catch (Exception e) {
                token1 = null;
            }
        }
        JsLoginUser jsLoginUser = jsLoginUserService.findUserByS(username);
        if (jsLoginUser == null) {
            return R.error("用户不存在");
        }
        boolean b = PasswordUtils.passwordCompare(password, jsLoginUser.getPassword());
        if (!b) {
            return R.error("密码错误");
        }
        String token = JWTUtil.createToken(jsLoginUser.getId()+"");
        redisService.set(token,jsLoginUser,1L);
        return R.ok().put("token", token);
    }

    //注册用户信息
    @PostMapping("login/create")
    public R loginCreate(@RequestBody JsLoginUser jsLoginUser) {
        //手机号没有，直接返回
        if (jsLoginUser.getTelephone() == null) {
            return R.error("没有手机号");
        }
        //没有姓名,直接返回
        if(jsLoginUser.getName()==null){
            return R.error("没有姓名");
        }
        //完善用户信息
        jsLoginUser = JsLoginUserUtil.newJsLoginUser(jsLoginUser);
        //保存用户信息
        boolean save = jsLoginUserService.save(jsLoginUser);
        if (!save) {
            return R.error("注册失败");
        }
        return R.ok();
    }

    //获取菜单列表
    @GetMapping("/menuList")
    public R viewMenu(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return R.error("没有token信息");
        }
        String userId = JWTUtil.getUserId(token);
        JsLoginUser jsLoginUser = jsLoginUserService.findUserRoleById(Integer.valueOf(userId));
        if (jsLoginUser == null) {
            return R.error("没有该用户");
        }
        List<JsRole> jsRoles = jsLoginUser.getJsRoles();
        HashMap<Integer, Permission> map = new HashMap<>();
        List<Permission> permissions = new ArrayList<>();
        for (JsRole jsRole : jsRoles) {
            List<Permission> permissions1 = jsRole.getPermissions();
            for (Permission permission : permissions1) {
//                Permission permission1 = map.get(permission.getParentId());
//                if(permission1!=null&&(permission.getType()!=0)){
//                    if(permission1.getChild()==null){
//                        List<Permission> s = new ArrayList<>();
//                        s.add(permission);
//                        permission1.setChild(s);
//                    }else{
//                        permission1.getChild().add(permission);
//                    }
//                }else {
//                    map.put(permission.getId(), permission);
//                }
            	map.put(permission.getId(), permission);
            }
            jsRole.setPermissions(null);
        }
        for (Integer integer : map.keySet()) {
            permissions.add(map.get(integer));
        }
        JSONArray a = TreeUtil.listToTree(JSONArray.parseArray(JSON.toJSONString(permissions)), "id", "parentId", "child");

        return R.ok().put("data", a);
    }

    //失败跳转位置
    @RequestMapping(path = "/unauthorized/{message}")
    public R unauthorized(@PathVariable String message) {
        return R.error(401, message);
    }

    //登录获取token,仅仅网页测试使用的接口
    @GetMapping("/login")
    public R logins(@RequestParam("username") String username, @RequestParam("password") String password) {
        JsLoginUser jsLoginUser = jsLoginUserService.findUserByS(username);
        if (jsLoginUser == null) {
            return R.error("用户不存在");
        }
        boolean b = PasswordUtils.passwordCompare(password, jsLoginUser.getPassword());
        if (!b) {
            return R.error("密码错误");
        }
        List<JsRole> jsRoles = jsLoginUser.getJsRoles();
        HashMap<Integer, Permission> map = new HashMap<>();
        List<Permission> permissions = new ArrayList<>();
        for (JsRole jsRole : jsRoles) {
            List<Permission> permissions1 = jsRole.getPermissions();
            for (Permission permission : permissions1) {
                map.put(permission.getId(), permission);
            }
            jsRole.setPermissions(null);
        }
        for (Integer integer : map.keySet()) {
            permissions.add(map.get(integer));
        }
        JSONArray a = TreeUtil.listToTree(JSONArray.parseArray(JSON.toJSONString(permissions)), "id", "parentId", "child");

        return R.ok().put("token", JWTUtil.createToken(jsLoginUser.getId()+"")).put("permission", a).put("user", jsLoginUser);
    }

}
